package cn.iocoder.yudao.module.def.service.attachment;

import org.springframework.stereotype.Service;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.def.controller.admin.attachment.vo.*;
import cn.iocoder.yudao.module.def.dal.dataobject.attachment.AttachmentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.def.dal.mysql.attachment.AttachmentMapper;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.def.enums.ErrorCodeConstants.*;

/**
 * 附件 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AttachmentServiceImpl implements AttachmentService {

    @Resource
    private AttachmentMapper attachmentMapper;

    @Override
    public Integer createAttachment(AttachmentSaveReqVO createReqVO) {
        // 插入
        AttachmentDO attachment = BeanUtils.toBean(createReqVO, AttachmentDO.class);
        attachmentMapper.insert(attachment);
        // 返回
        return attachment.getId();
    }

    @Override
    public void updateAttachment(AttachmentSaveReqVO updateReqVO) {
        // 校验存在
        validateAttachmentExists(updateReqVO.getId());
        // 更新
        AttachmentDO updateObj = BeanUtils.toBean(updateReqVO, AttachmentDO.class);
        attachmentMapper.updateById(updateObj);
    }

    @Override
    public void deleteAttachment(Integer id) {
        // 校验存在
        validateAttachmentExists(id);
        // 删除
        attachmentMapper.deleteById(id);
    }

    private void validateAttachmentExists(Integer id) {
        if (attachmentMapper.selectById(id) == null) {
            throw exception(ATTACHMENT_NOT_EXISTS);
        }
    }

    @Override
    public AttachmentDO getAttachment(Integer id) {
        return attachmentMapper.selectById(id);
    }

    @Override
    public PageResult<AttachmentDO> getAttachmentPage(AttachmentPageReqVO pageReqVO) {
        return attachmentMapper.selectPage(pageReqVO);
    }

}